package com.luo.backend.service;

import com.luo.backend.dto.CategoryResponse;
import com.luo.backend.dto.FoodPreviewDTO;
import com.luo.backend.dto.FoodResponse;
import com.luo.backend.dto.MerchantResponse;
import com.luo.backend.entity.Food;
import com.luo.backend.entity.FoodCategory;
import com.luo.backend.entity.Merchant;
import com.luo.backend.repository.FoodCategoryRepository;
import com.luo.backend.repository.FoodRepository;
import com.luo.backend.repository.MerchantRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商家商品服务类
 */
@Service
public class MerchantService {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantService.class);
    
    @Autowired
    private MerchantRepository merchantRepository;
    
    @Autowired
    private FoodRepository foodRepository;
    
    @Autowired
    private FoodCategoryRepository categoryRepository;
    
    /**
     * 获取商家列表（分页）
     */
    public Map<String, Object> getMerchants(int page, int limit, String keyword, String sort, Integer status) {
        logger.info("获取商家列表: page={}, limit={}, keyword={}, sort={}, status={}", 
                   page, limit, keyword, sort, status);
        
        Pageable pageable;
        
        // 根据排序方式创建分页对象
        if ("rating".equals(sort)) {
            pageable = PageRequest.of(page - 1, limit, Sort.by(Sort.Direction.DESC, "rating", "ratingCount"));
        } else if ("ratingCount".equals(sort)) {
            pageable = PageRequest.of(page - 1, limit, Sort.by(Sort.Direction.DESC, "ratingCount"));
        } else if ("createdAt".equals(sort)) {
            pageable = PageRequest.of(page - 1, limit, Sort.by(Sort.Direction.DESC, "createdAt"));
        } else {
            // 默认按评分排序
            pageable = PageRequest.of(page - 1, limit, Sort.by(Sort.Direction.DESC, "rating", "ratingCount"));
        }
        
        Page<Merchant> merchantPage;
        
        // 根据条件查询
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 关键词搜索
            merchantPage = merchantRepository.findByNameContaining(keyword.trim(), pageable);
        } else if (status != null) {
            // 按状态过滤
            merchantPage = merchantRepository.findByStatus(status, pageable);
        } else {
            // 默认只返回营业中的商家
            merchantPage = merchantRepository.findByStatus(1, pageable);
        }
        
        // 转换为响应DTO
        List<MerchantResponse> merchants = merchantPage.getContent().stream()
                .map(MerchantResponse::new)
                .collect(Collectors.toList());
        
        // 批量查询菜品数量和预览菜品
        if (!merchants.isEmpty()) {
            enrichMerchantsWithFoodInfo(merchants);
        }
        
        // 构建分页信息
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("current_page", page);
        pagination.put("per_page", limit);
        pagination.put("total", merchantPage.getTotalElements());
        pagination.put("total_pages", merchantPage.getTotalPages());
        
        // 构建响应
        Map<String, Object> result = new HashMap<>();
        result.put("merchants", merchants);
        result.put("pagination", pagination);
        
        return result;
    }
    
    /**
     * 批量为商家添加菜品数量和预览菜品信息
     */
    private void enrichMerchantsWithFoodInfo(List<MerchantResponse> merchants) {
        // 获取所有商家ID
        List<Long> merchantIds = merchants.stream()
                .map(MerchantResponse::getId)
                .collect(Collectors.toList());
        
        // 批量查询每个商家的菜品数量
        Map<Long, Long> foodCountMap = new HashMap<>();
        for (Long merchantId : merchantIds) {
            Long count = foodRepository.countByMerchantIdAndStatus(merchantId, 1);
            foodCountMap.put(merchantId, count);
        }
        
        // 批量查询预览菜品
        List<Food> allPreviewFoods = foodRepository.getPreviewFoodsByMerchantIds(merchantIds);
        
        // 按商家ID分组，每个商家最多取3个
        Map<Long, List<FoodPreviewDTO>> previewFoodsMap = new HashMap<>();
        for (Food food : allPreviewFoods) {
            Long merchantId = food.getMerchantId();
            previewFoodsMap.putIfAbsent(merchantId, new ArrayList<>());
            
            List<FoodPreviewDTO> previewList = previewFoodsMap.get(merchantId);
            if (previewList.size() < 3) {
                previewList.add(new FoodPreviewDTO(food));
            }
        }
        
        // 设置每个商家的菜品信息
        for (MerchantResponse merchant : merchants) {
            Long merchantId = merchant.getId();
            
            // 设置菜品数量
            Long foodCount = foodCountMap.getOrDefault(merchantId, 0L);
            merchant.setFoodCount(foodCount.intValue());
            
            // 设置预览菜品
            List<FoodPreviewDTO> previewFoods = previewFoodsMap.getOrDefault(merchantId, new ArrayList<>());
            merchant.setPreviewFoods(previewFoods);
        }
    }
    
    /**
     * 获取商家详情
     */
    public MerchantResponse getMerchantById(Long id) {
        logger.info("获取商家详情: id={}", id);
        
        Optional<Merchant> merchantOpt = merchantRepository.findById(id);
        if (!merchantOpt.isPresent()) {
            throw new RuntimeException("商家不存在");
        }
        
        return new MerchantResponse(merchantOpt.get());
    }
    
    /**
     * 获取商家商品列表
     */
    public List<FoodResponse> getMerchantFoods(Long merchantId, Long categoryId, String keyword, 
                                               Boolean isHot, Boolean isRecommended) {
        logger.info("获取商家商品: merchantId={}, categoryId={}, keyword={}, isHot={}, isRecommended={}", 
                   merchantId, categoryId, keyword, isHot, isRecommended);
        
        // 验证商家是否存在
        if (!merchantRepository.existsById(merchantId)) {
            throw new RuntimeException("商家不存在");
        }
        
        List<Food> foods;
        
        // 根据不同条件查询商品
        if (categoryId != null) {
            foods = foodRepository.findByMerchantIdAndCategoryId(merchantId, categoryId);
        } else if (keyword != null && !keyword.trim().isEmpty()) {
            foods = foodRepository.findByMerchantIdAndNameContaining(merchantId, keyword.trim());
        } else if (isHot != null && isHot) {
            foods = foodRepository.findByMerchantIdAndIsHot(merchantId, 1);
        } else if (isRecommended != null && isRecommended) {
            foods = foodRepository.findByMerchantIdAndIsRecommended(merchantId, 1);
        } else {
            foods = foodRepository.findByMerchantId(merchantId);
        }
        
        // 转换为响应DTO
        return foods.stream()
                .map(food -> {
                    FoodResponse response = new FoodResponse(food);
                    // 如果有分类ID，设置分类信息
                    if (food.getCategoryId() != null) {
                        Optional<FoodCategory> categoryOpt = categoryRepository.findById(food.getCategoryId());
                        if (categoryOpt.isPresent()) {
                            FoodCategory category = categoryOpt.get();
                            response.setCategory(new FoodResponse.CategoryInfo(category.getId(), category.getName()));
                        }
                    }
                    return response;
                })
                .collect(Collectors.toList());
    }
    
    /**
     * 获取商品详情
     */
    public FoodResponse getFoodById(Long id) {
        logger.info("获取商品详情: id={}", id);
        
        Optional<Food> foodOpt = foodRepository.findById(id);
        if (!foodOpt.isPresent()) {
            throw new RuntimeException("商品不存在");
        }
        
        Food food = foodOpt.get();
        FoodResponse response = new FoodResponse(food);
        
        // 设置商家信息
        Optional<Merchant> merchantOpt = merchantRepository.findById(food.getMerchantId());
        if (merchantOpt.isPresent()) {
            Merchant merchant = merchantOpt.get();
            FoodResponse.MerchantInfo merchantInfo = new FoodResponse.MerchantInfo(
                merchant.getId(), merchant.getName(), 
                merchant.getMinOrderAmount(), merchant.getDeliveryFee());
            merchantInfo.setLogo(merchant.getLogo()); // ⭐ 设置商家Logo
            response.setMerchant(merchantInfo);
        }
        
        // 设置分类信息
        if (food.getCategoryId() != null) {
            Optional<FoodCategory> categoryOpt = categoryRepository.findById(food.getCategoryId());
            if (categoryOpt.isPresent()) {
                FoodCategory category = categoryOpt.get();
                response.setCategory(new FoodResponse.CategoryInfo(category.getId(), category.getName()));
            }
        }
        
        return response;
    }
    
    /**
     * 搜索商品（全局搜索）
     */
    public Map<String, Object> searchFoods(String keyword, int page, int limit) {
        logger.info("全局搜索商品: keyword={}, page={}, limit={}", keyword, page, limit);
        
        if (keyword == null || keyword.trim().isEmpty()) {
            throw new RuntimeException("搜索关键词不能为空");
        }
        
        Pageable pageable = PageRequest.of(page - 1, limit);
        Page<Food> foodPage = foodRepository.searchByKeyword(keyword.trim(), pageable);
        
        // 转换为响应DTO
        List<FoodResponse> foods = foodPage.getContent().stream()
                .map(FoodResponse::new)
                .collect(Collectors.toList());
        
        // 构建分页信息
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("current_page", page);
        pagination.put("per_page", limit);
        pagination.put("total", foodPage.getTotalElements());
        pagination.put("total_pages", foodPage.getTotalPages());
        
        // 构建响应
        Map<String, Object> result = new HashMap<>();
        result.put("foods", foods);
        result.put("pagination", pagination);
        
        return result;
    }
    
    /**
     * 获取商品分类列表
     */
    public List<CategoryResponse> getFoodCategories() {
        logger.info("获取商品分类列表");
        
        List<FoodCategory> categories = categoryRepository.findByStatusOrderBySortOrderAscCreatedAtAsc(1);
        return categories.stream()
                .map(CategoryResponse::new)
                .collect(Collectors.toList());
    }
}